package com.pan.service;

import com.pan.constants.DatabaseInfo;
import com.pan.dao.User;
import com.pan.dao.UserDAO;
import com.pan.dao.UserDAOImpl;
import com.pan.util.CheckAuth;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/download")
public class DownloadFile extends HttpServlet {
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String token = request.getParameter("token");
        if (!CheckAuth.checkToken(token)) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
            return;
        }
        UserDAO userDAO = UserDAOImpl.getInstance();
        User user = userDAO.getUserByToken(token);
        String filePath = DatabaseInfo.FILE_PATH + "\\" + user.getFilePath() + "\\";

        String path = request.getParameter("path");
        if (path != null) {
            path = java.net.URLDecoder.decode(path, "UTF-8");
        }

        String fileName = request.getParameter("fileName");
        if (fileName != null) {
            fileName = java.net.URLDecoder.decode(fileName, "UTF-8");
        }

        String fullPath = filePath + path + "\\" + fileName;

        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        response.setContentType("application/octet-stream");

        try (java.io.FileInputStream in = new java.io.FileInputStream(fullPath);
             java.io.OutputStream out = response.getOutputStream()) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "File not found");
        }
    }
}
